package com.example.controller;

import com.example.handler.NettyClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;

/*
 *  @author 雨安
 *  类名： NettyClientController
 *  创建时间：2024/3/8
 */
@RestController
public class NettyClientController {
    @RequestMapping("/test")
    void test(@RequestParam(required = false)String context) throws InterruptedException {
        //1.创建线程组
        EventLoopGroup group = new NioEventLoopGroup();
        //2.创建客户端启动助手
        Bootstrap bootstrap = new Bootstrap();
        //3.设置线程组
        bootstrap.group(group)
                .channel(NioSocketChannel.class) //4.设置客户端通道实现为NIO
                .handler(new ChannelInitializer<SocketChannel>() { //5.创建一个通道初始化对象
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new NettyClientHandler());
                    }
                });
        //6.启动客户端 等待连接服务器,同时将异步改为同步
        ChannelFuture channelFuture = bootstrap.connect("127.0.0.1",9999).sync();
        //使用Netty转换工具发送消息
        channelFuture.channel().writeAndFlush(Unpooled.copiedBuffer(context.getBytes(StandardCharsets.UTF_8)));
        //7.关闭通道和连接池 这里就是一把锁
        channelFuture.channel().closeFuture().sync();
        group.shutdownGracefully();
    }

}
